package org.kernely.ui.admin;

import java.util.Dictionary;
import java.util.Hashtable;
import java.util.Set;

import org.kernely.security.dao.UserDetailsDAO;
import org.kernely.security.persistence.UserDetails;
import org.kernely.ui.MainApplication;
import org.kernely.ui.home.KernelyHomeView;
import org.kernely.ui.mvp.KernelyPresenter;
import org.kernely.ui.mvp.ViewIdentifier;
import org.kernely.ui.services.KernelyUIBundle;
import org.kernely.ui.utils.KernelyNotification;

import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickListener;
/**
 * Presenter class of the administration of Kernely.
 */

public class KernelyAdministrationPagePresenter extends KernelyPresenter<KernelyAdministrationPageView> {

	/**
	 * @see org.kernely.ui.mvp.KernelyPresenter#bind()
	 */
	@SuppressWarnings("serial")
	public void bind() {

		// Kernely default page
		ViewIdentifier defaultPage = new ViewIdentifier("Kernely default home page",(KernelyHomeView.class).toString(),MainApplication.getBundleName());
		this.view.getHomePagesBox().addItem(defaultPage);
		this.view.getHomePagesBox().setItemCaption(defaultPage,"Kernely default home page");
		this.view.getHomePagesBox().setValue(defaultPage);

		UserDetailsDAO uddao = UserDetailsDAO.getInstance();
		UserDetails details = uddao.getUserDetails(MainApplication.getSecurityService().getCurrentUser());
		// TODO : replace with the default page in config file
		String currentView = details.getHomepageview();
		String currentBundle = details.getHomepagebundle();
		
		// All other pages
		for (KernelyUIBundle bundle : MainApplication.getKernelyUIBundleService().getUIBundles()){
			// If the bundle provides home pages
			Set<ViewIdentifier> pages = bundle.getFrontPages();
			if(pages != null){
				for (ViewIdentifier viewIdentifier : pages){
					this.view.getHomePagesBox().addItem(viewIdentifier);
					this.view.getHomePagesBox().setItemCaption(viewIdentifier,
							viewIdentifier.getViewName() + " ("+ bundle.getName()+")");
					if (viewIdentifier.getViewClass().equals(currentView) && viewIdentifier.getViewBundleName().equals(currentBundle)){
						this.view.getHomePagesBox().setValue(viewIdentifier);
					}
					
				}
			}

		}
		this.view.getApplyButton().addListener(new ClickListener(){
			/**
			 * Called when a ClickEvent is fired
			 */
			public void buttonClick (Button.ClickEvent event) {
				ViewIdentifier identifier = (ViewIdentifier) view.getHomePagesBox().getValue();
				Dictionary properties = new Hashtable();
				properties.put(MainApplication.getDbkeyHomepageClass(), identifier.getViewClass());
				properties.put(MainApplication.getDbkeyHomepageBundle(), identifier.getViewBundleName());
				
				MainApplication.getSettingsService().newProperties(MainApplication.getBundleName(), properties);
				view.getWindow().showNotification(new KernelyNotification("The default page has been changed to " + identifier.getViewName()+".",KernelyNotification.INFO_ICON));
			}
		});


	}

}
